/*
 Xern Entity Relocation Network
 Copyright (C) 2010-2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#include <boost/lexical_cast.hpp>
#include <boost/uuid/uuid_io.hpp>
#include "Xern/IResourceLoadedCallback.hpp"
#include "Xern/DataFilter.hpp"
#include "Xern/FilterStream.hpp"
#include "Xern/Log.hpp"
#include "Xern/Exceptions.hpp"
#include "Xern/Engine.hpp"
#include "Xern/ResourceManager.hpp"
#include "CompoundShape.hpp"

namespace XernBullet
{
	// SubShapeLoadedCallback.
	class SubShapeLoadedCallback: public IResourceLoadedCallback
	{
	public:
		SubShapeLoadedCallback(boost::shared_ptr<CompoundShape> shape, const Transform &transform);
		~SubShapeLoadedCallback();

		virtual void OnLoadedResource(boost::shared_ptr<IResource> resource);

	private:
		boost::shared_ptr<CompoundShape> shape;
		Transform transform;
	};

	SubShapeLoadedCallback::SubShapeLoadedCallback(boost::shared_ptr<CompoundShape> shape, const Transform &transform)
		: shape(shape), transform(transform)
	{
	}

	SubShapeLoadedCallback::~SubShapeLoadedCallback()
	{
	}

	void SubShapeLoadedCallback::OnLoadedResource(boost::shared_ptr<IResource> resource)
	{
		boost::shared_ptr<ICollisionShape> subshape = boost::dynamic_pointer_cast<ICollisionShape> (resource);
		if(!subshape)
			throw XernException("Expected collision shape.");

		// Add the sub-shape.
		shape->AddShape(transform, subshape);
	}

	// CompoundShape
	CompoundShape::CompoundShape()
	{
		compoundShape = new btCompoundShape(true);
	}

	CompoundShape::~CompoundShape()
	{
		delete compoundShape;
	}

	// ICompoundShape
	void CompoundShape::AddShape(const Transform &transform,
			boost::shared_ptr<ICollisionShape> shape)
	{
		// Extract the bullet shape.
		boost::shared_ptr<IBulletShape> bshape =
				boost::dynamic_pointer_cast<IBulletShape> (shape);
		if(!bshape)
			throw XernException("Expected bullet shape");

		// Convert the position.
		const Vector3 &loc = transform.GetVector();
		btVector3 bloc(loc.x, loc.y, loc.z);;

		// Convert the quaternion.
		const Quaternion &rot = transform.GetRotation();
		btQuaternion brot(rot.x, rot.y, rot.z, rot.w);

		// Convert the transformation.
		btTransform btrans;
		btrans.setOrigin(bloc);
		btrans.setRotation(brot);

		// Add the sub shape.
		compoundShape->addChildShape(btrans, bshape->GetBulletShape());

		// Store a copy of the shape.
		SubshapeData data;
		data.shape = shape;
		data.transform = transform;
		subShapes.push_back(data);
	}

	// IBulletShape
	btCollisionShape *CompoundShape::GetBulletShape()
	{
		return compoundShape;
	}

	// Serialization.
	const char *CompoundShape::GetMimeType() const
	{
		return "application/vnd.cshape.compound";
	}

	void CompoundShape::UpdateState(boost::shared_ptr<IDataFilter> stateData)
	{
		// Inmutable.
	}

	boost::shared_ptr<IDataFilter> CompoundShape::GetSerializedData() const
	{
		// Create the json object.
		JsonObject object;

		// Create the subshape array
		JsonValue &arrayValue = object["subshapes"] = JsonArray();
		JsonArray &subShapes = boost::get<JsonArray> (arrayValue);

		// Store each sub shape data.
		size_t numsubshapes = this->subShapes.size();
		for(size_t i = 0; i < numsubshapes; i++)
		{
			JsonObject subshape;
			const SubshapeData &data = this->subShapes[i];
			subshape["guid"] = boost::lexical_cast<std::string> (data.shape->GetId());
			subshape["position"] = boost::lexical_cast<std::string> (data.transform.GetVector());
			subshape["rotation"] = boost::lexical_cast<std::string> (data.transform.GetRotation());
			subShapes.push_back(subshape);
		}

		// Serialize the data.
		boost::shared_ptr<StringFilter> filter(new StringFilter());
		filter->GetStream() << object << std::ends;

		// Return the data.
		return filter;
	}

	boost::shared_ptr<CompoundShape>
	CompoundShape::DeSerialize(boost::shared_ptr<IDataFilter> data)
	{
		try
		{
			// Create the filter stream
			FilterStream in(data);

			// Read the json object.
			JsonObject object;
			in >> object;

			// Create the shape.
			boost::shared_ptr<CompoundShape> ret(new CompoundShape());

			// Get the subshapes array.
			const JsonArray &subshapes = boost::get<const JsonArray&> (object["subshapes"]);
			size_t numsubshapes = subshapes.size();
			for(size_t i = 0; i < numsubshapes; i++)
			{
				// Get the subshape.
				const JsonObject &subshape = boost::get<JsonObject> (subshapes[i]);

				// Get his id.
				uuid id = boost::lexical_cast<uuid> (boost::get<JsonString> (subshape["guid"]).string());

				// Get his transform.
				Transform trans;
				trans.SetVector(boost::lexical_cast<Vector3> (boost::get<const JsonString&> (subshape["position"]).string()));
				trans.SetRotation(boost::lexical_cast<Quaternion> (boost::get<const JsonString&> (subshape["rotation"]).string()));

				// Request the subshape over the network.
				boost::shared_ptr<SubShapeLoadedCallback> callback(new SubShapeLoadedCallback(ret, trans));
				Engine::Get().GetResourceManager()->DelayedLoad(id, callback);
			}

			return ret;
		}
		catch(const XernException &e)
		{
			LogConsole->Error("Failed to read box shape data: %s", e.what());
		}
		catch(const boost::bad_get &e)
		{
			LogConsole->Error("Incomplete box shape data.");
		}

		return boost::shared_ptr<CompoundShape> ();
	}
}; // namespace XernBullet
